import { loginAPI } from '@/api/user'
import { removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: () => {
    return {
      token: ''
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      // 清除cookie中的token
      removeToken()
    }
  },
  actions: {
    async doLogin(ctx, { username, password }) {
      try {
        // 1、 调用接口
        const res = await loginAPI({ username, password })
        // 2、提交mutation
        ctx.commit('setToken', res.data.token)
      } catch (error) {
        console.error('登录失败:', error)
        throw error // 抛出错误以便在组件中处理
      }
    }
  }
}
